package com.gxuwz.medical.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.chronicdis.Chronicdis;
import com.gxuwz.medical.domain.chronicinfo.Chronicinfo;
import com.gxuwz.medical.domain.family.Family;
import com.gxuwz.medical.domain.family.FamilyMember;
import com.gxuwz.medical.domain.vo.Page;
import com.gxuwz.medical.exception.DbException;

public class ChronicInfoDao extends GenericDao<Chronicinfo> {
	
	@Override
	protected Chronicinfo handle(ResultSet rs) throws SQLException {
		
		Chronicinfo entity=new Chronicinfo();
		entity.setId(rs.getString("id"));
		try {
			entity.setMembercode(new FamilyMember(rs.getString("membercode")));
		} catch (DbException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
		try {
			entity.setIllcode(new Chronicdis(rs.getString("illcode")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		entity.setCreator(rs.getString("creator"));
		entity.setCreattime(rs.getDate("creattime"));
		entity.setEndtime(rs.getString("endtime"));
		entity.setStarttime(rs.getString("starttime"));
		entity.setStatus(rs.getString("status"));
		return entity;
	}

	
	/**
	 * 分页
	 * @param sql
	 * @param params
	 * @param page
	 * @param size
	 * @return
	 * @throws SQLException
	 */
		public Page queryOjectsByPage(String sql,Object[]params,int pageNo,int size)throws SQLException{
			Connection conn =null;
			PreparedStatement pstmt=null;
			ResultSet rs=null;
			Page page=null;
			List<Chronicinfo> datas=new ArrayList<Chronicinfo>();
			try{
				int start=(pageNo-1)*size;
				conn=DbUtil.getConn();
				pstmt=conn.prepareStatement(sql+" limit "+start+","+size);
				int index=1;
				if(params!=null){
				  for(Object param:params){
					  if(param instanceof String){
						  pstmt.setString(index++, (String)param);
					  }
					  if(param instanceof Integer){
						  pstmt.setInt(index++, (Integer)param);
					  }
					  if(param instanceof Float){
						  pstmt.setFloat(index++, (Float)param);
					  }
				  }
				}
				rs=pstmt.executeQuery();
				while(rs.next()){
					Chronicinfo chronicinfo=handle(rs);
					datas.add(chronicinfo);
				}
				//统计SQL对应记录数
				int total=count(sql, params);
				page=new Page(total, pageNo, size, datas);
				return page;
			}catch(SQLException e){
				e.printStackTrace();
				throw e;
			}
			
		}
}
